<script setup lang="ts">
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'
import type { Props, Emits, Options } from './utils/types'
import APICommon from '@/api/common'
import { ElLoading, ElMessage } from 'element-plus'
import { useAuth } from '@/stores/index'
import APIInformation from '@/api/information'

const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()
const { getInfo } = useAuth()
const { info } = storeToRefs(useAuth())

const dialogVisible = shallowRef(false)

watch($props, (newValue) => {
    dialogVisible.value = newValue.modelValue
}, { immediate: true })


watch(dialogVisible, (newValue) => {
    $emit('update:modelValue', newValue)
})

const imageRef = shallowRef<HTMLImageElement>()
const previewRef = shallowRef<HTMLDivElement>()
const cropper = shallowRef()

const options: Options = {
    aspectRatio: 1 / 1,
    dragMode: 'move',
    viewMode: 1,
    autoCropArea: 1
}


function onOpen() {
    if (!imageRef.value || !previewRef.value) return
    options.preview = previewRef.value
    cropper.value = new Cropper(imageRef.value, (options as object))
}

function onChange(e: Event) {
    const dom = e.target as HTMLInputElement
    if (!dom.files) return
    const file = dom.files[0]
    if (file.size / 1024 / 1024 > 2) {
        dom.value = ''
        return ElMessage.error('头像图片大小不能超过2MB！')
    }
    const url = URL.createObjectURL(file)
    cropper.value.replace(url)
    dom.value = ''
}

const fileRef = shallowRef<HTMLInputElement>()

function handleSelectAvatar() {
    fileRef.value?.click()
}

function getCroppedFile(): Promise<File> {
    return new Promise((resovle) => {
        const canvas = cropper.value.getCroppedCanvas()
        canvas.toBlob((blob: any) => {
            const file = new File([blob], 'cropped_image.jpg', { type: 'image/jpeg' })
            resovle(file)
        }, 'image/jpeg', 0.7)
    })
}

async function handleUpload() {
    const file: File = await getCroppedFile()
    info.value.head_img = URL.createObjectURL(file)
    const form = new FormData()
    form.append('file', file)
    const loading = ElLoading.service({ lock: true })
    APICommon.uploadFile(form).then(({ data }) => {
        return APIInformation.changePersonal({ head_img: data.file })
    }).then(({ msg }) => {
        dialogVisible.value = false
        ElMessage.success(msg)
    }).finally(() => {
        loading.close()
    })

}

</script>

<template>
    <el-dialog class="edit-avatar" v-model="dialogVisible" title="设置头像" width="800" destroy-on-close @open="onOpen"
        :show-close="false">
        <template #header>
            <DialogClose title="设置头像" @close="dialogVisible = false" />
        </template>
        <div class="container">
            <div class="preview" ref="previewRef"></div>
            <div class="cropper-box">
                <img id="image" ref="imageRef" src="./images/default.png" alt="default" />
            </div>
        </div>
        <input type="file" ref="fileRef" style="display: none;" @change="onChange">
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="handleSelectAvatar">选择头像</el-button>
                <el-button type="primary" @click="handleUpload">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.edit-avatar {
    .container {
        display: flex;
        justify-content: space-between;
        padding: 35px 90px;
        padding-top: 45px;

        .cropper-box {
            width: 360px;
            height: 240px;
            overflow: hidden;
            background-color: #d7d7d7;

            #image {
                display: block;
                max-width: 100%;
            }
        }

        .preview {
            width: 150px;
            height: 150px;
            overflow: hidden;
        }
    }
}
</style>
